from fastapi import APIRouter
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request

from main import app

router = APIRouter()
#  中间件是全局的
#  ==================== 中间件 ====================
# 中间件就是全局的
# 第一种创建方式
@app.middleware("http")
async def http_middle_1(request: Request, call_next):
    print("--- 进入 @app.middleware('http') 中间件")
    response = await call_next(request)
    print("--- 退出 @app.middleware('http') 中间件")
    return response


# 第二种创建方式
class HttpMiddleImpl(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        print("--- 进入 BaseHTTPMiddleware 中间件")
        response = await call_next(request)
        print("--- 退出 BaseHTTPMiddleware 中间件")
        return response


app.add_middleware(HttpMiddleImpl)


# 第三种
async def http_middle_2(request: Request, call_next):
    print("--- 进入 fun_middle 中间件")
    response = await call_next(request)
    print("--- 退出 fun_middle 中间件")
    return response


app.middleware("http")(http_middle_2)

